package com.weixin.base.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.weixin.base.service.RoleService;
import com.weixin.base.util.ExtJsPageHelper;
import com.weixin.base.util.ListRange;
import com.weixin.entity.BgRight;

@Controller
public class RoleAction {

	@Autowired
	private RoleService roleService;
	
	/**
	 * 添加角色
	 */
	@RequestMapping(value = "/module/main/addRole.do", method = RequestMethod.POST)
	public void addRole(HttpServletRequest request,HttpServletResponse response)throws IOException {
		
		String result="";
		
		try {
			String sname = request.getParameter("sname");
			String sremark = request.getParameter("sremark");
			
			BgRight bgright=new BgRight();
			bgright.setSname(sname);
			bgright.setSremark(sremark);
			
			roleService.addRole(bgright);
			
			result="true";
		} catch (Exception e) {
			result="false";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 角色查询
	 */
	@RequestMapping(value = "/module/main/searchRole.do")
	public void searchRole(HttpServletRequest request,HttpServletResponse response)throws IOException {
		
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		Page page = roleService.findByPageRequest(pr);
		
		List<BgRight> TbBgRightlist = (List) page.getResult();
		ListRange<BgRight> resultList = new ListRange<BgRight>();
		resultList.setList(TbBgRightlist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		
		response.setContentType("text/javascript;charset=UTF-8");
		ObjectMapper objectMapper =new ObjectMapper();
		String result=objectMapper.defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
		
	}
	
	/**
	 * 修改角色
	 */
	@RequestMapping(value = "/module/main/upRole.do", method = RequestMethod.POST)
	public void upRole(HttpServletRequest request,HttpServletResponse response)throws IOException {
		
		String result="";
		
		try {
			String sname = request.getParameter("sname");
			String sremark = request.getParameter("sremark");
			int nisValid = Integer.parseInt(request.getParameter("nisValid"));
			int nrightId = Integer.parseInt(request.getParameter("nrightId"));
			
			BgRight bgright=new BgRight();
			bgright.setNisValid(nisValid);
			bgright.setNrightId(nrightId);
			bgright.setSname(sname);
			bgright.setSremark(sremark);
			
			roleService.upRole(bgright);
			
			result="true";
		} catch (Exception e) {
			result="false";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 角色删除
	 */
	@RequestMapping(value = "/module/main/delRole.do", method = RequestMethod.POST)
	public void delRole(HttpServletRequest request,HttpServletResponse response)throws IOException {
		
		String ids = request.getParameter("ids");
		String result = "";
		try{
			roleService.deleteRoleById(Integer.parseInt(ids));
			result = "true";
		}
		catch (Exception e){
			result = "false";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 查询角色菜单读写权限
	 */
	@RequestMapping(value = "/module/main/selectRoleMPermiss.do")
	public void selectRoleMPermiss(HttpServletRequest request,HttpServletResponse response) {
		int nRoleId = Integer.parseInt(request.getParameter("nRoleId"));
		try {
			
			List<Map<String,Object>> rtList=roleService.selectRoleMPermiss(nRoleId);
			
			response.getWriter().print(new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(rtList));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改角色菜单读写权限
	 */
	@RequestMapping(value = "/module/main/updateRoleMPermiss.do")
	public void updateRoleMPermiss(HttpServletRequest request,HttpServletResponse response)throws IOException {
		String result="";
		int nRoleId = Integer.parseInt(request.getParameter("nRoleId"));
		try {
			String permissRws=request.getParameter("permissRws");
			roleService.updateRoleMPermiss(nRoleId,permissRws);
			
			result="true";
		} catch (Exception e) {
			result="false";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 查询角色菜单
	 */
	@RequestMapping(value = "/module/main/selectRolePermiss.do")
	public void selectRolePermiss(HttpServletRequest request,HttpServletResponse response) {
		int nRoleId = Integer.parseInt(request.getParameter("nRoleId"));
		try {
			response.getWriter().print("["+rolePermissTreeIntoJson(roleService.selRolePermiss(nRoleId))+"]");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *处理角色菜单树转为json
	 * @param smap
	 */
	public String rolePermissTreeIntoJson(Map<String, Object> smap){
		
		try {
			ObjectMapper obm=new ObjectMapper();
			//获取所有功能treeList
			List<Map<String,Object>> treeList=(List<Map<String,Object>>)smap.get("ary_all");
			List<Map<String,Object>> ary_role=(List<Map<String,Object>>)smap.get("ary_role");
			
			//设置功能根节点
			Map<String,Object> rootMap=new HashMap<String, Object>();
			rootMap.put("expanded", "true");
			if(treeList!=null){
				
				/**
				 * 初始化数据 hasPermiss:1-拥有；2-没有 0- 全部都没有拥有权限 1表示有权限
				 * leaf true 全部都为叶子节点
				 * nRW false-只读；true-可读写 初始全部为可读
				 */
				for (Map<String, Object> maptree : treeList) {
					maptree.put("leaf", true);
					maptree.put("checked", false);
					maptree.put("text", maptree.get("sName")==null?"":maptree.get("sName"));
//					maptree.put("hasPermiss", 0);
//					maptree.put("nRW", false);
				}
				
				if(ary_role!=null){
					for (Map<String, Object> mapary : ary_role) {
						
						for (Map<String, Object> maptree : treeList) {
							
							if(maptree.get("nNavTreeId").equals(mapary.get("nNavTreeId"))){
//								maptree.put("hasPermiss", 1);
								maptree.put("checked", true);
//								if(mapary.get("nRW").equals(2)){
//									maptree.put("nRW", true);
//								}
							}
						}
						
					}
				}
				
				addTreeMap(treeList,rootMap);
				return obm.defaultPrettyPrintingWriter().writeValueAsString(rootMap);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
	/**
	 * 树结构处理
	 * @param treeList -全部节点
	 * @param rootMap  -根结点
	 * nPId 值为 父节点ID
	 * nNavTreeId 值为 节点ID
	 */
	public void addTreeMap(List<Map<String,Object>> treeList,Map<String,Object> rootMap){
		
		for (int i=0;i<treeList.size();i++) {
			Map<String,Object> mmp=treeList.get(i);
			
			//nPId为0 表示为跟节点 所以复制其中内容进入根结点集合rootMap 然后从全部节点treeList中删除
			if(mmp.get("nPId").equals(0)){
				rootMap.putAll(mmp);
				treeList.remove(mmp);
				i--;
				continue;
			}
			if(rootMap.get("nNavTreeId")!=null){
				
				//如果节点mmp的父节点为rootMap的ID 则放入其children集合中
				if(mmp.get("nPId").equals(rootMap.get("nNavTreeId"))){
					
					if(rootMap.get("children")==null){
						rootMap.put("children", new ArrayList<Map<String,Object>>());
					}
					
					((ArrayList<Map<String,Object>>)rootMap.get("children")).add(mmp);
					rootMap.put("leaf", false);
					rootMap.put("disabled",true);
					rootMap.put("expanded", true);
					treeList.remove(mmp);
					i--;
				}
			}
		}
		
		if(treeList.size()>0){
			//如果节点rootMap 拥有子节点 则将子节点与剩下的节点treeList 做为参数递归
			if(rootMap.get("children")!=null){
				for (Map<String, Object> srootMap : (ArrayList<Map<String,Object>>)rootMap.get("children")) {
					addTreeMap(treeList,srootMap);
				}
			}
		}
	}
	
	/**
	 * 更新权限
	 */
	@RequestMapping(value = "/module/main/upRolePermiss.do", method = RequestMethod.POST)
	public void upRolePermiss(HttpServletRequest request,HttpServletResponse response)throws IOException {
		String result = "";
		int nRoleId = Integer.parseInt(request.getParameter("nRoleId"));
		String nNavTrees = request.getParameter("nNavTrees");
		try{
			roleService.upDelRolePermiss(nRoleId, nNavTrees);
			result = "true";
		}catch(Exception e){
			result = "false";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 返回页面
	 */
	@RequestMapping("/module/main/roleManager.do")
	public String registPost(HttpServletRequest request,HttpServletResponse response) {
			String roleId=request.getParameter("roleId");
			request.setAttribute("roleId", roleId);
			return "/manager/RoleManager";
	}
		
}
